<?php

namespace lxs\tools;

use App\Models\system\ApiAuthModel;
use App\Models\users\UsersModel;
use Carbon\Carbon;
use lxs\auth\AesSecret;
use lxs\config\System;

class Tools
{

    public static function dump($value): void
    {
        echo '<pre>' . print_r($value, true) . '</pre>';
    }

    /**
     * 获取或配置系统参数
     * @param string $name 参数名称
     * @param mixed|null $value 参数内容
     * @return mixed
     */
    public static function Config(string $name = '', mixed $value = null): mixed
    {
        if (is_null($value) && is_string($name)) {
            try {
                return System::instance()->get($name);
            } catch (\Exception $ex) {
                return null;
            }
        } else {
            try {
                return System::instance()->set($name, $value);
            } catch (\Exception $ex) {
                return false;
            }
        }
    }

    /**
     * 时间格式转换
     * @param $time int|string 时间戳/date字符串
     * @param $format string 时间格式
     */
    public static function timeConvert(int|string $time, string $format='Y-m-d H:i:s'): float|bool|int|string
    {
        if (is_numeric($time) && $time > 0) {
            return date($format, $time);
        } else if (strtotime($time) !== false) {
            return Carbon::parse($time)->timestamp;
        } else {
            return '';
        }
    }


    /**
     * 检查是否时间戳
     */
    public static function isTimestamp($time): bool
    {
        if (!is_numeric($time)) {
            return false;
        }
        if(strtotime(date('Y-m-d H:i:s',$time)) === (int)$time) {
            return true;
        }
        return false;
    }


    /**
     * 生成唯一编码
     * @param string $name
     * @param int $number
     * @return string
     */
    public static function uniqidDate(string $name='', int $number = 16): string
    {

        $numbers = range(0, 9);
        shuffle($numbers);
        $num = 3;
        $random = implode('', array_slice($numbers, 0, $num));
        (int)$code = $random . date('YmdHis');

        if ($number > 0) {
            if (strlen($number) > 1) {
                $length = strlen($number) - 1;
                $code = substr($code, $length) . rand(0, $number);
            } else {
                $code .= $number;
            }
        } else {
            $code .= rand(0, 9);
        }
        return $name . $code;
    }


    /**
     * 生成唯一手机编码
     */
    public static function getUniqueMobile(): string
    {
        $num = UsersModel::count() + 1;
        $temp_num = 100000;
        $new_num = $num + $temp_num;
        $real_num = substr($new_num, 0, 6);

        return rand(0, 99) . $real_num . rand(0, 99);
    }


    /**
     * 生成小程序程序码参数
     */
    public static function getQrcodeCode($unique_id, $product_id): string
    {
        return "unique={$unique_id}&pro={$product_id}";
    }


    /**
     * 无限级分类
     * @param array $data 数据
     * @param int $pid 父级id
     * @param int $level 级别
     */
    public static function getTree(array $data, int $pid = 0, int $level = 0): array
    {
        $arr = [];
        foreach ($data as $v) {
            if ($v['pid'] == $pid) {
                $v['level'] = $level;
                $v['children'] = self::getTree($data, $v['id'], $level + 1);
                $arr[] = $v;
            }
        }
        return $arr;
    }


    /**
     * 通过数字获取指定月份的第一天和最后一天
     * @param string $yearMonth 日期
     * @param bool $is_format 是否返回时间戳
     * @return array
     */
    public static function getTheMonth(string $yearMonth, bool $is_format=true): array
    {
        if ($yearMonth == '') {
            $firstday = date('Y-m-01 00:00:00');
            $lastday = date('Y-m-d H:i:s', time());
        } else {
            $year = substr($yearMonth, 0, 4);
            $month = substr($yearMonth, 5, 2);
            $firstday = date('Y-m-d 00:00:00', mktime(0, 0, 0, $month, 1, $year));
            $lastday = date('Y-m-d 23:59:59', mktime(0, 0, 0, $month + 1, 0, $year));
        }

        if ($is_format === false) {
            $firstday = strtotime($firstday);
            $lastday = strtotime($lastday);
        }
        return array($firstday, $lastday);
    }


    /**
     * 二进制转图片image/png
     * @param string $contents 二进制内容
     * @param string $mime image/jpeg
     * @return string
     */
    public static function binaryToImage(string $contents, string $mime='image/png'): string
    {
        $base64 = base64_encode($contents);
        return ('data:' . $mime . ';base64,' . $base64);
    }


    /**
     * 判断是否为正常图片
     * @param $img_file
     * @return bool
     */
    public static function isImage($img_file): bool
    {
        $img_info = getimagesize($img_file);
        if ($img_info !== false) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * curl请求
     * @param $url
     * @param string|array $post_data
     * @param string $method
     * @param array $header
     * @return bool|string
     */
    public static function httpRequest($url, string|array $post_data='', string $method='GET', array $header=[]): bool|string
    {
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'default-user-agent';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

            if ($post_data != '' || $post_data != null) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }


    /**
     * 隐藏号码
     * @param string $value 原字符串
     * @param string $type 隐藏类型 phone/bank
     * @return string
     */
    public static function hideNumber(string $value, string $type='phone'): string
    {
        if (strlen($value) > 4) {
            if ($type === 'phone') {
                return substr($value, 0, 3) . '****' . substr($value, -4);
            } else if ($type === 'bank') {
                return '尾号' . substr($value, -4);
            }
        } else {
            return $value;
        }
    }


    /**
     * 检查子字符串是否在原字符串中出现
     * @param string $str 原字符串
     * @param string $substr 子字符串
     */
    public static function checkSubstr(string $str, string $substr): bool
    {
        $nums=substr_count($str,$substr);
        if ($nums>=1)
        {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 截取字符串’-‘后的字符串
     */
    public static function interceptCustomStr(string $str, string $symbol='-'): string
    {
        if (!str_contains($str, $symbol)) {
            return $str;
        }
        $str = explode('-', $str);
        return $str[1];
    }




}
